<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Spring Security 认证功能测试</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 900px;
            margin: 0 auto;
        }

        .header {
            text-align: center;
            color: white;
            margin-bottom: 30px;
        }

        .header h1 {
            font-size: 32px;
            margin-bottom: 10px;
        }

        .card {
            background: white;
            border-radius: 10px;
            padding: 25px;
            margin-bottom: 20px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        .card h2 {
            color: #667eea;
            margin-bottom: 15px;
            border-bottom: 2px solid #667eea;
            padding-bottom: 10px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #333;
            font-weight: bold;
        }

        .form-group input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }

        .form-group input:focus {
            outline: none;
            border-color: #667eea;
        }

        button {
            background: #667eea;
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            font-weight: bold;
            transition: background 0.3s;
        }

        button:hover {
            background: #5568d3;
        }

        button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }

        .result {
            margin-top: 15px;
            padding: 15px;
            border-radius: 5px;
            display: none;
        }

        .result.success {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }

        .result.error {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }

        .result pre {
            margin-top: 10px;
            padding: 10px;
            background: rgba(0, 0, 0, 0.05);
            border-radius: 3px;
            overflow-x: auto;
            font-size: 12px;
        }

        .token-display {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            border: 1px solid #dee2e6;
            margin-top: 15px;
            display: none;
        }

        .token-display h3 {
            color: #667eea;
            margin-bottom: 10px;
            font-size: 16px;
        }

        .token-display p {
            word-break: break-all;
            color: #666;
            font-size: 12px;
            line-height: 1.6;
        }

        .info-box {
            background: #e7f3ff;
            border-left: 4px solid #2196F3;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 3px;
        }

        .info-box h3 {
            color: #2196F3;
            margin-bottom: 8px;
        }

        .info-box p {
            color: #555;
            line-height: 1.6;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🔐 Spring Security 认证功能测试</h1>
            <p>测试用户注册、登录和Token认证功能</p>
        </div>

        <div class="info-box">
            <h3>📌 使用说明</h3>
            <p>
                1. 先点击"测试连接"确保后端服务正常运行<br>
                2. 注册一个新用户（或使用管理员账号：admin / admin123）<br>
                3. 登录获取Token<br>
                4. 使用Token访问受保护的接口
            </p>
        </div>

        <!-- 测试连接 -->
        <div class="card">
            <h2>🌐 测试连接</h2>
            <button onclick="testConnection()">测试后端连接</button>
            <div id="testResult" class="result"></div>
        </div>

        <!-- 用户注册 -->
        <div class="card">
            <h2>📝 用户注册</h2>
            <div class="form-group">
                <label>用户名</label>
                <input type="text" id="registerUsername" placeholder="3-32个字符，只能包含字母数字下划线" value="testuser">
            </div>
            <div class="form-group">
                <label>密码</label>
                <input type="password" id="registerPassword" placeholder="6-32个字符" value="123456">
            </div>
            <div class="form-group">
                <label>确认密码</label>
                <input type="password" id="registerConfirmPassword" placeholder="再次输入密码" value="123456">
            </div>
            <div class="form-group">
                <label>显示昵称</label>
                <input type="text" id="registerDisplayName" placeholder="2-50个字符" value="测试用户">
            </div>
            <button onclick="register()">注册</button>
            <div id="registerResult" class="result"></div>
            <div id="registerToken" class="token-display"></div>
        </div>

        <!-- 用户登录 -->
        <div class="card">
            <h2>🔑 用户登录</h2>
            <div class="form-group">
                <label>用户名</label>
                <input type="text" id="loginUsername" placeholder="请输入用户名" value="admin">
            </div>
            <div class="form-group">
                <label>密码</label>
                <input type="password" id="loginPassword" placeholder="请输入密码" value="admin123">
            </div>
            <button onclick="login()">登录</button>
            <div id="loginResult" class="result"></div>
            <div id="loginToken" class="token-display"></div>
        </div>

        <!-- 检查用户名 -->
        <div class="card">
            <h2>🔍 检查用户名是否可用</h2>
            <div class="form-group">
                <label>用户名</label>
                <input type="text" id="checkUsername" placeholder="请输入要检查的用户名" value="admin">
            </div>
            <button onclick="checkUsername()">检查</button>
            <div id="checkResult" class="result"></div>
        </div>

        <!-- 获取当前用户信息 -->
        <div class="card">
            <h2>👤 获取当前用户信息（需要认证）</h2>
            <p style="color: #666; margin-bottom: 15px;">此接口需要Token认证，请先登录</p>
            <button onclick="getCurrentUserInfo()">获取用户信息</button>
            <div id="currentUserResult" class="result"></div>
        </div>

        <!-- 获取指定用户信息 -->
        <div class="card">
            <h2>🔎 获取指定用户信息（需要认证）</h2>
            <p style="color: #666; margin-bottom: 15px;">此接口需要Token认证，请先登录</p>
            <div class="form-group">
                <label>用户ID</label>
                <input type="number" id="userId" placeholder="请输入用户ID" value="1">
            </div>
            <button onclick="getUserInfo()">获取信息</button>
            <div id="userInfoResult" class="result"></div>
        </div>

        <!-- 清除Token -->
        <div class="card">
            <h2>🗑️ 清除Token</h2>
            <p style="color: #666; margin-bottom: 15px;">清除本地存储的Token</p>
            <button onclick="clearToken()" style="background: #dc3545;">清除Token</button>
            <div id="clearResult" class="result"></div>
        </div>
    </div>

    <script>
        const API_BASE = 'http://localhost:8080';

        // 显示结果
        function showResult(elementId, success, message, data) {
            const element = document.getElementById(elementId);
            element.className = 'result ' + (success ? 'success' : 'error');
            element.innerHTML = `
                <strong>${success ? '✅ 成功' : '❌ 失败'}</strong>
                <p>${message}</p>
                ${data ? '<pre>' + JSON.stringify(data, null, 2) + '</pre>' : ''}
            `;
            element.style.display = 'block';
        }

        // 显示Token
        function showToken(elementId, token, data) {
            const element = document.getElementById(elementId);
            element.innerHTML = `
                <h3>🎫 Token已保存到localStorage</h3>
                <p><strong>Token:</strong> ${token}</p>
                <p><strong>用户ID:</strong> ${data.userId}</p>
                <p><strong>用户名:</strong> ${data.username}</p>
                <p><strong>角色:</strong> ${data.role}</p>
            `;
            element.style.display = 'block';
        }

        // 测试连接
        async function testConnection() {
            try {
                const response = await fetch(`${API_BASE}/api/hello/world`);
                const result = await response.json();
                showResult('testResult', true, '后端服务连接正常', result);
            } catch (error) {
                showResult('testResult', false, '连接失败：' + error.message);
            }
        }

        // 用户注册
        async function register() {
            const username = document.getElementById('registerUsername').value;
            const password = document.getElementById('registerPassword').value;
            const confirmPassword = document.getElementById('registerConfirmPassword').value;
            const displayName = document.getElementById('registerDisplayName').value;

            try {
                const response = await fetch(`${API_BASE}/api/auth/register`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        username,
                        password,
                        confirmPassword,
                        displayName
                    })
                });

                const result = await response.json();

                if (result.code === 200) {
                    localStorage.setItem('token', result.data.token);
                    showResult('registerResult', true, '注册成功！', result.data);
                    showToken('registerToken', result.data.token, result.data);
                } else {
                    showResult('registerResult', false, result.message || '注册失败', result);
                }
            } catch (error) {
                showResult('registerResult', false, '请求失败：' + error.message);
            }
        }

        // 用户登录
        async function login() {
            const username = document.getElementById('loginUsername').value;
            const password = document.getElementById('loginPassword').value;

            try {
                const response = await fetch(`${API_BASE}/api/auth/login`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        username,
                        password
                    })
                });

                const result = await response.json();

                if (result.code === 200) {
                    localStorage.setItem('token', result.data.token);
                    showResult('loginResult', true, '登录成功！', result.data);
                    showToken('loginToken', result.data.token, result.data);
                } else {
                    showResult('loginResult', false, result.message || '登录失败', result);
                }
            } catch (error) {
                showResult('loginResult', false, '请求失败：' + error.message);
            }
        }

        // 检查用户名
        async function checkUsername() {
            const username = document.getElementById('checkUsername').value;

            try {
                const response = await fetch(`${API_BASE}/api/auth/check-username?username=${username}`);
                const result = await response.json();

                if (result.code === 200) {
                    const available = result.data;
                    showResult('checkResult', true, 
                        available ? '✅ 用户名可用' : '❌ 用户名已存在', 
                        result.data);
                } else {
                    showResult('checkResult', false, result.message || '检查失败', result);
                }
            } catch (error) {
                showResult('checkResult', false, '请求失败：' + error.message);
            }
        }

        // 获取当前用户信息
        async function getCurrentUserInfo() {
            const token = localStorage.getItem('token');

            if (!token) {
                showResult('currentUserResult', false, '请先登录获取Token');
                return;
            }

            try {
                const response = await fetch(`${API_BASE}/api/auth/current`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                const result = await response.json();

                if (result.code === 200) {
                    showResult('currentUserResult', true, '获取用户信息成功', result.data);
                } else if (result.code === 401) {
                    showResult('currentUserResult', false, 'Token无效或已过期，请重新登录', result);
                } else {
                    showResult('currentUserResult', false, result.message || '获取失败', result);
                }
            } catch (error) {
                showResult('currentUserResult', false, '请求失败：' + error.message);
            }
        }

        // 获取指定用户信息（需要Token）
        async function getUserInfo() {
            const userId = document.getElementById('userId').value;
            const token = localStorage.getItem('token');

            if (!userId) {
                showResult('userInfoResult', false, '请输入用户ID');
                return;
            }

            if (!token) {
                showResult('userInfoResult', false, '请先登录获取Token');
                return;
            }

            try {
                const response = await fetch(`${API_BASE}/api/auth/user/${userId}`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                const result = await response.json();

                if (result.code === 200) {
                    showResult('userInfoResult', true, '获取用户信息成功', result.data);
                } else if (result.code === 401) {
                    showResult('userInfoResult', false, 'Token无效或已过期，请重新登录', result);
                } else {
                    showResult('userInfoResult', false, result.message || '获取失败', result);
                }
            } catch (error) {
                showResult('userInfoResult', false, '请求失败：' + error.message);
            }
        }

        // 清除Token
        function clearToken() {
            localStorage.removeItem('token');
            showResult('clearResult', true, 'Token已清除');
        }

        // 页面加载时检查是否有Token
        window.onload = function() {
            const token = localStorage.getItem('token');
            if (token) {
                console.log('已存储Token:', token);
            }
        };
    </script>
</body>
</html>

